package database;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import dataPO.*;
import databaseInterface.DiscTicketManageInterface;

public class DiscTicketManage implements DiscTicketManageInterface{
	private Statement stmt;
	private DatabaseConnection db= new DatabaseConnection();
	// the discount rate should not be less than 0 , judged in the client 

	
	public void connect (){        
         stmt =db.connect();
    }
    

  
	public void insert (DiscountCouponsPO d){  	 
		String insert ="insert into discTicket (disRate) values ("+d.getDiscount()+")";

        try {
			stmt.executeUpdate(insert);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
    

	public void delete (double disc){   	
    	String delete="delete from discTicket  where disRate = "+disc;
    	try {
			stmt.executeUpdate(delete);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }


	public void update (DiscountCouponsPO d, double disc){    	
    	String update ="update discTicket set discRate = "+ d.getDiscount()+" where disRate = "+disc ;
        try {
			stmt.executeUpdate(update);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
    }

	public boolean exist(double discRate){
    	String query = "select * from discTicket where disRate = "+String.valueOf(discRate);
    	ArrayList<DiscountCouponsPO> tlist = search (query);
    	if (tlist.isEmpty()) return false;
    	else return true ;	
    }
	
	public ArrayList<DiscountCouponsPO> query (){
    	String query = "select * from discTicket  ";
    	ArrayList<DiscountCouponsPO> tlist =search (query);
    	return tlist;	
    }
	
	private ArrayList<DiscountCouponsPO> search (String str){
    	ArrayList<DiscountCouponsPO> tlist = new ArrayList<DiscountCouponsPO> ();
     	try {
			ResultSet rs= stmt.executeQuery(str);
			while(rs.next()){
	    		DiscountCouponsPO d= toDiscountCouponsPO(rs);
	    	    tlist.add(d);
	    	
	    	}		    	    	
    	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    	
    	return tlist;	
    }
	
    private DiscountCouponsPO toDiscountCouponsPO(ResultSet rs) {
	// TODO Auto-generated method stub
    	DiscountCouponsPO d = new DiscountCouponsPO();
    	try {
    		d.setDiscount(rs.getDouble("disRate"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return d;
    }

        
    public  void close(){	      
    	db.close();
    }
	

    
}